import rclpy
from rclpy.node import Node
from example_interfaces.msg import String
from queue import Queue
import threading
import espeakng
import time

class NovelSubNode(Node):
    def __init__(self,node_name):
        super().__init__(node_name)
        self.get_logger().info(f'{node_name},启动！')
        self.novels_queue_ = Queue() # 创建队列，用于存储小说内容
        # 创建话题订阅者，订阅小说内容
        self.novel_subscriber_ = self.create_subscription(String,'novel',self.novel_callback,10)
        self.speech_thread_ = threading.Thread(target=self.speech_thread_func)
        self.speech_thread_.start()

    def novel_callback(self,msg):
        self.novels_queue_.put(msg.data) # 将小说内容放入队列中

    def speech_thread_func(self):
        speaker = espeakng.Speaker()
        speaker.voice = 'zh'
        while rclpy.ok():
            if not self.novels_queue_.empty():
                text = self.novels_queue_.get()
                self.get_logger().info(f'正在朗读：{text}')
                speaker.say(text)
                speaker.wait()
            else:
                time.sleep(1)



def main():
    rclpy.init()
    node = NovelSubNode('novel_sub_node')

    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()